# API文档地址： https://fanyi-api.baidu.com/product/113
from email.policy import default
import hashlib
import json
from random import randint
import time
import urllib.request
import urllib.parse

MAX_RESP_TIME = 5
REQUEST_FAILED = -1# 请求失败码
LANS = ['auto','zh','en','jp','kor']
encoding = 'utf-8' # 编码用utf-8
default_options = {
    'appid': '',
    'salt': 777,
    'from': '',
    'to': '',
    'q': '',
    'sign': ''
}

class BaiduTran:
    SECRET_KEY = ''
    options = default_options
    
    def __init__(self, config):
        self.initTran(config)
        self.initOptions(config)

    def initTran(self, config):
        self.SECRET_KEY = config['BAIDU_TRAN_SECRET_KEY']

    def initOptions(self, config):
        self.options['appid'] = config['BAIDU_TRAN_APP_ID']
        self.options['salt'] = str(randint(777, 10000))
        self.options['from'] = LANS[config['SOURCE_LANGUAGE']]
        self.options['to'] =  LANS[config['TARGET_LANGUAGE']+1]

    def trans(self, content):
        url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
        self.options['q'] = content
        self.options['sign'] = getMD5(self.options['appid'] + content + self.options['salt'] + self.SECRET_KEY)
        html = getTranslateResponce(url, self.options)
        res = json.loads(html)
        i = 0 
        while i < MAX_RESP_TIME:
            if res.get('error_code') != REQUEST_FAILED:
                break
            i += 1
            print('本次请求失败，原因为：', res['error_msg'])
            time.sleep(1)
            html = getTranslateResponce(url, self.options)
            res = json.loads(html)
        print(res)
        return self.parse(res)

    # 解析翻译结果
    def parse(self, res):
        if res.get('error_code'):
            return res['error_msg']
        elif res.get('trans_result'):
            return res['trans_result'][0]['dst']
        return '未知错误'

def getMD5(content):
    return hashlib.md5(content.encode(encoding)).hexdigest()

def getTranslateResponce(url, data):
    data = urllib.parse.urlencode(data).encode(encoding)
    response = urllib.request.urlopen(url, data)
    return response.read().decode(encoding)
